package goods

import (
	"context"
	"encoding/json"
	"sale-admin/config/mysql"
	"sale-admin/internal/app/grpc/client"
	"sale-admin/internal/app/grpc/protoc/system_admin"
	"sale-admin/internal/dal"
	"sale-admin/internal/dao"
	"strconv"
	"strings"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/logx"
	"github.com/samber/lo"
)

func (GoodsService) GetExpressFee(
	ctx context.Context,
	goodsID string,
	shippingProvince string, // 可以是名称，也可以是id
) (float64, error) {
	goodsDetail, _ := dao.Goods{}.Detail(ctx, dal.Q, goodsID)
	if goodsDetail == nil {
		return 0.00, errorx.New("商品不存在", -1)
	}
	// 没有设置模版，使用默认模版
	expressFeeDetail := dao.ExpressFeeSetting{}.Detail(ctx, mysql.NewDB(), goodsDetail.ExpressFeeTemplate)
	if expressFeeDetail == nil {
		expressFeeDetail := dao.ExpressFeeSetting{}.GetDefault(ctx, mysql.NewDB())
		if expressFeeDetail == nil {
			return 0.00, errorx.New("运费模版不存在", -1)
		}
	}
	freeShippingProvince := expressFeeDetail.FreeShippingProvince
	freeShippingProvinceIDs := strings.Split(freeShippingProvince, ",")
	_, err := strconv.Atoi(shippingProvince)
	if err != nil {
		cli, err := client.GetSystemAdminClient()
		if err != nil {
			logx.Error(context.Background(), "GetSystemAdminClient err", logx.Err(err))
			return 0.00, errorx.New("获取运费信息失败", -1)
		}
		rsp, err := cli.ProvinceList(ctx, &system_admin.ProvinceListReq{})
		if err != nil {
			logx.Error(context.Background(), "ProvinceListReq err", logx.Any("rsp", rsp), logx.Err(err))
			return 0.00, errorx.New("获取运费信息失败", -1)
		}
		for _, area := range rsp.Areas {
			if area.Name == shippingProvince {
				shippingProvince = area.ID // 使用id
				break
			}
		}
	}
	// 包邮
	if lo.Contains(freeShippingProvinceIDs, shippingProvince) {
		return 0.00, nil
	}
	var expressFeeConfig []dao.PricingConfigT
	json.Unmarshal([]byte(expressFeeDetail.PricingConfig), &expressFeeConfig)
	for _, config := range expressFeeConfig {
		if config.Province == shippingProvince {
			if len(config.Config) <= 0 {
				return 0.00, errorx.New("该地区不支持配送", -1)
			} else {
				return config.Config[0].Price, nil
			}
		}
	}
	return 0.00, errorx.New("该地区不支持配送", -1)
}
